/// faichou  2017-01-04
var app = getApp()
var util=require('../../utils/util')
var dialog=require('../../utils/dialog')
var req=require('./addressReq.js')
Page({
	data:{
		isLogin: true,
		userId: '',
		addrArray: []
	},
	onLoad: function(){
	},
	onShow: function(){
		// 判断用户是否登陆了
		let that=this
		if (false) {
			dialog.warn('请先登录')
			this.setData({
				isLogin: false
			})
		}else{
			this.setData({
				isLogin: true
			})
			req.requestAllAddr(function(data){
					console.log(data)
					let resArr = data.returnData.currentList
					that.setData({
			    	addrArray: resArr
			    })
				}, function(err){
					dialog.warn('获取失败，请稍后重试')
				})
			
		}
	},
	// 进入添加地址
	addAddress: function(){
		let addressEditPath = './addressEdit?justAdd=1'
		app.globalData.receiveInfo = null // 添加地址，receiveInfo都为空
		wx.navigateTo({
		  url: addressEditPath
		})
	},
	// 设为默认地址
	setDefault: function(data){
		// set default address
		let that=this
		let addrId = data.currentTarget.dataset.addrid
		let indexA = data.currentTarget.dataset.index
		let defaultAddr = that.data.addrArray[indexA]
		defaultAddr.isDefault = true
		let originAddrArray = that.data.addrArray
		
		req.editAddress(addrId, defaultAddr, function(){
			console.log('默认地址设置成功')
			originAddrArray.forEach(function(item, index){
				if (indexA!==index) {
					item.isDefault=false
				}else{
					item.isDefault=true
					wx.setStorage({
						key: 'Address',
						data: item,
					})
				}
			})
			that.setData({
				addrArray: originAddrArray
			})

			
		}, function(){
			console.log('默认地址设置失败')
		})
	},
	// 进入编辑地址页面
	editAddress: function(data) {
		let index = data.currentTarget.dataset.index
		let addressEditPath = './addressEdit?justAdd=0'
		app.globalData.receiveInfo = this.data.addrArray[index]
		wx.navigateTo({
		  url: addressEditPath
		})
	},
	// 删除地址
	deleteAddress: function(data){
		let that=this
		let addrId = data.currentTarget.dataset.addrid
		let index = data.currentTarget.dataset.index
		var originAddrArray = this.data.addrArray
		// var newAddrArray = originAddrArray.splice(index) // 天大的坑
		originAddrArray.splice(index, 1)
		wx.showModal({
			title: "确定删除？",
			content: "",
			showCancel: true,
			cancelText: "取消",
			cancelColor: "#000000",
			confirmText: "确定",
			confirmColor: "#3CC51F",
			success: function(res) {
				// ATTENTION: 这个success不是点击确认的回调
				if (res.confirm) {
						req.delAddress(addrId, function(){
						dialog.toast('删除成功')
						that.setData({
							addrArray: originAddrArray
						})
					},function(){
						dialog.warn('删除失败，稍后重试')
					})
				}
				
			},
			fail: function (res) {
				
			},
			complete: function (res) {
				
			}
		});
	}
})
